import angular from 'angular';
import multiLevelTreeTemplate from './multi-level-tree.template.html';

multiLevelTreeDirective.$inject = ['$timeout', '$sce'];

function multiLevelTreeDirective($timeout, $sce) {
  return {
    restrict: 'E',
    template: multiLevelTreeTemplate,
    scope: {
      treeData: '=',
      id: '@',
      label: '@',
      cascade: '=?',
      multiple: '=?',
      cascadeReturnParentOnly: '=?',
      ngModel: '=',
      searchable: '=?',
      searchPlaceholder: '@?'
    },
    link: function(scope) {
      // 默认配置
      scope.idField = scope.id || 'BpaId';
      scope.labelField = scope.label || 'cnName';
      scope.cascade = scope.cascade !== undefined ? scope.cascade : true;
      scope.multiple = scope.multiple !== undefined ? scope.multiple : true;
      scope.cascadeReturnParentOnly = scope.cascadeReturnParentOnly !== undefined ? scope.cascadeReturnParentOnly : false;
      scope.searchable = scope.searchable !== undefined ? scope.searchable : false;

      // 搜索相关
      scope.searchKeyword = '';
      scope.searchResults = [];

      console.log('Tree component initialized, searchable:', scope.searchable);

      // 初始化选中的节点
      scope.selectedIds = scope.ngModel || [];

      // 展开选中的ID（如果启用了 cascadeReturnParentOnly，需要展开父节点ID）
      function expandSelectedIds(ids) {
        if (!scope.cascadeReturnParentOnly || !scope.cascade) {
          return ids;
        }

        var expanded = [];
        var addedSet = {};

        ids.forEach(function(id) {
          if (addedSet[id]) return;

          var node = nodeMap[id];
          if (!node) return;

          // 添加节点本身
          expanded.push(id);
          addedSet[id] = true;

          // 如果有子节点，递归添加所有子节点
          var childIds = getAllChildIds(node);
          childIds.forEach(function(childId) {
            if (!addedSet[childId]) {
              expanded.push(childId);
              addedSet[childId] = true;
            }
          });
        });

        return expanded;
      }

      // 监听外部 ngModel 变化
      scope.$watch('ngModel', function(newVal) {
        if (newVal && angular.isArray(newVal)) {
          // 展开ID列表（如果是简化后的父节点ID，需要展开为包含所有子节点）
          var expandedIds = expandSelectedIds(newVal);
          scope.selectedIds = angular.copy(expandedIds);
          updateTreeCheckState();
        }
      }, true);

      // 构建节点映射和父子关系
      var nodeMap = {};
      var parentChildMap = {};

      function buildNodeMap(nodes, parent) {
        if (!nodes || !angular.isArray(nodes)) return;

        nodes.forEach(function(node) {
          var nodeId = node[scope.idField];
          nodeMap[nodeId] = node;

          // 初始化节点状态（只在属性不存在时初始化）
          if (node.checked === undefined) {
            node.checked = false;
          }
          if (node.indeterminate === undefined) {
            node.indeterminate = false;
          }
          if (node.expanded === undefined) {
            node.expanded = false;
          }

          // 建立父子关系
          if (parent) {
            var parentId = parent[scope.idField];
            if (!parentChildMap[parentId]) {
              parentChildMap[parentId] = [];
            }
            parentChildMap[parentId].push(nodeId);
          }

          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            buildNodeMap(node.children, node);
          }
        });
      }

      // 根据选中的ID更新树的选中状态
      function updateTreeCheckState() {
        // 重置所有节点状态
        Object.keys(nodeMap).forEach(function(nodeId) {
          nodeMap[nodeId].checked = false;
          nodeMap[nodeId].indeterminate = false;
        });

        // 设置选中状态
        scope.selectedIds.forEach(function(id) {
          if (nodeMap[id]) {
            nodeMap[id].checked = true;
          }
        });

        // 如果启用级联，更新父节点的半选状态
        if (scope.cascade) {
          updateParentStates();
        }
      }

      // 更新父节点状态
      function updateParentStates() {
        function updateParent(node) {
          if (!node || !node.children || node.children.length === 0) return;

          var checkedCount = 0;
          var indeterminateCount = 0;

          node.children.forEach(function(child) {
            if (child.checked) {
              checkedCount++;
            }
            if (child.indeterminate) {
              indeterminateCount++;
            }
          });

          if (checkedCount === node.children.length) {
            node.checked = true;
            node.indeterminate = false;
          } else if (checkedCount > 0 || indeterminateCount > 0) {
            node.checked = false;
            node.indeterminate = true;
          } else {
            node.checked = false;
            node.indeterminate = false;
          }
        }

        // 从叶子节点向上更新
        function traverseUp(nodes) {
          if (!nodes) return;
          nodes.forEach(function(node) {
            if (node.children && node.children.length > 0) {
              traverseUp(node.children);
              updateParent(node);
            }
          });
        }

        traverseUp(scope.treeData);
      }

      // 获取节点的所有子节点ID
      function getAllChildIds(node) {
        var ids = [];
        if (!node || !node.children || node.children.length === 0) {
          return ids;
        }

        node.children.forEach(function(child) {
          ids.push(child[scope.idField]);
          ids = ids.concat(getAllChildIds(child));
        });

        return ids;
      }

      // 获取节点的所有父节点ID
      function getAllParentIds(nodeId) {
        var ids = [];
        var currentNode = nodeMap[nodeId];

        if (!currentNode) return ids;

        // 查找父节点
        function findParent(nodes, targetId, parentNode) {
          if (!nodes) return null;

          for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i];
            if (node[scope.idField] === targetId) {
              return parentNode;
            }
            if (node.children && node.children.length > 0) {
              var found = findParent(node.children, targetId, node);
              if (found) return found;
            }
          }
          return null;
        }

        var parent = findParent(scope.treeData, nodeId, null);
        while (parent) {
          ids.push(parent[scope.idField]);
          parent = findParent(scope.treeData, parent[scope.idField], null);
        }

        return ids;
      }

      // 简化选中的ID列表（只保留最顶层的父节点）
      function simplifySelectedIds(selectedIds) {
        if (!scope.cascadeReturnParentOnly || !scope.cascade) {
          return selectedIds;
        }

        var simplified = [];
        var selectedSet = {};
        var processedParents = {};

        // 构建已选中ID的集合
        selectedIds.forEach(function(id) {
          selectedSet[id] = true;
        });

        // 第一步：检查是否有父节点的所有子节点都被选中，如果是，将父节点加入简化列表
        Object.keys(nodeMap).forEach(function(nodeId) {
          var node = nodeMap[nodeId];
          if (!node || !node.children || node.children.length === 0) return;

          // 检查该节点的所有子节点是否都在选中列表中
          var childIds = getAllChildIds(node);
          if (childIds.length === 0) return;

          var allChildrenSelected = childIds.every(function(childId) {
            return selectedSet[childId];
          });

          // 如果所有子节点都被选中，标记这个父节点
          if (allChildrenSelected) {
            processedParents[nodeId] = true;
            // 将父节点加入到选中集合（用于后续判断）
            selectedSet[nodeId] = true;
          }
        });

        // 第二步：遍历所有选中的节点，过滤掉那些父节点已经被包含的节点
        selectedIds.forEach(function(id) {
          var node = nodeMap[id];
          if (!node) return;

          // 检查该节点的所有父节点
          var parentIds = getAllParentIds(id);
          var shouldInclude = true;

          // 如果任何父节点的所有子节点都被选中，则跳过当前节点
          for (var i = 0; i < parentIds.length; i++) {
            var parentId = parentIds[i];
            if (processedParents[parentId]) {
              shouldInclude = false;
              break;
            }
          }

          if (shouldInclude) {
            simplified.push(id);
          }
        });

        // 第三步：添加那些通过"所有子节点选中"推导出来的父节点
        Object.keys(processedParents).forEach(function(parentId) {
          // 检查这个父节点是否应该被更高层的父节点替代
          var parentNode = nodeMap[parentId];
          if (!parentNode) return;

          var parentParentIds = getAllParentIds(parentId);
          var shouldInclude = true;

          for (var i = 0; i < parentParentIds.length; i++) {
            if (processedParents[parentParentIds[i]]) {
              shouldInclude = false;
              break;
            }
          }

          if (shouldInclude && simplified.indexOf(parentId) === -1) {
            simplified.push(parentId);
          }
        });

        return simplified;
      }

      function removeFromSelected(id) {
        var index = scope.selectedIds.indexOf(id);
        if (index !== -1) {
          scope.selectedIds.splice(index, 1);
        }
      }

      // 切换节点选中状态
      scope.toggleCheck = function(node) {
        var nodeId = node[scope.idField];
        var isChecked = !node.checked;

        if (scope.multiple) {
          // 多选模式
          if (isChecked) {
            // 选中节点
            if (scope.selectedIds.indexOf(nodeId) === -1) {
              scope.selectedIds.push(nodeId);
            }

            // 如果启用级联，选中所有子节点
            if (scope.cascade) {
              var childIds = getAllChildIds(node);
              childIds.forEach(function(id) {
                if (scope.selectedIds.indexOf(id) === -1) {
                  scope.selectedIds.push(id);
                }
              });
            }
          } else {
            // 取消选中节点
            removeFromSelected(nodeId);

            // 如果启用级联，取消选中所有子节点
            if (scope.cascade) {
              var childIds = getAllChildIds(node);
              childIds.forEach(function(id) {
                removeFromSelected(id);
              });

              // 同步移除所有祖先节点，避免保留已不完整选中状态
              var parentIds = getAllParentIds(nodeId);
              parentIds.forEach(function(parentId) {
                removeFromSelected(parentId);
              });
            }
          }
        } else {
          // 单选模式
          scope.selectedIds = isChecked ? [nodeId] : [];
        }

        // 更新 ngModel（如果启用了 cascadeReturnParentOnly，则简化ID列表）
        var idsToReturn = simplifySelectedIds(scope.selectedIds);

        // 使用 splice 更新数组内容，而不是替换引用，以保持与父组件的双向绑定
        if (scope.ngModel) {
          scope.ngModel.length = 0;
          Array.prototype.push.apply(scope.ngModel, idsToReturn);
        } else {
          scope.ngModel = angular.copy(idsToReturn);
        }

        // 更新树状态
        updateTreeCheckState();
      };

      // 切换展开/折叠
      scope.toggleExpand = function(node, $event) {
        if ($event) {
          $event.stopPropagation();
        }

        $timeout(function() {
          node.expanded = !node.expanded;
        });
      };

      // 判断节点是否有子节点
      scope.hasChildren = function(node) {
        return node.children && node.children.length > 0;
      };

      // 搜索节点
      function searchNodes(nodes, keyword) {
        var results = [];
        if (!nodes || !keyword) {
          console.log('searchNodes: nodes or keyword is empty', {nodes: !!nodes, keyword: keyword});
          return results;
        }

        keyword = keyword.toLowerCase();
        console.log('searchNodes: searching for keyword:', keyword, 'in field:', scope.labelField);

        var checkedCount = 0;
        function traverse(nodeList) {
          nodeList.forEach(function(node) {
            checkedCount++;
            var label = (node[scope.labelField] || '').toLowerCase();
            if (label.indexOf(keyword) !== -1) {
              console.log('Match found:', label, 'contains', keyword);
              results.push(node);
            }
            if (node.children && node.children.length > 0) {
              traverse(node.children);
            }
          });
        }

        traverse(nodes);
        console.log('searchNodes: checked', checkedCount, 'nodes, found', results.length, 'matches');
        return results;
      }

      // 展开节点的所有父节点
      function expandParents(node) {
        var parentIds = getAllParentIds(node[scope.idField]);
        parentIds.forEach(function(parentId) {
          var parentNode = nodeMap[parentId];
          if (parentNode) {
            parentNode.expanded = true;
          }
        });
      }

      // 清除所有高亮
      function clearAllHighlights() {
        Object.keys(nodeMap).forEach(function(nodeId) {
          nodeMap[nodeId].highlighted = false;
        });
      }

      // 高亮文本 - 使用缓存避免无限循环
      var highlightCache = {};
      scope.highlightText = function(text) {
        if (!text) {
          return text;
        }

        if (!scope.searchKeyword) {
          return text;
        }

        // 使用缓存键避免重复计算
        var cacheKey = scope.searchKeyword + '::' + text;
        if (highlightCache[cacheKey]) {
          return highlightCache[cacheKey];
        }

        var keyword = scope.searchKeyword;
        var regex = new RegExp('(' + keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
        var highlightedText = text.replace(regex, '<span class="search-highlight">$1</span>');
        var result = $sce.trustAsHtml(highlightedText);

        highlightCache[cacheKey] = result;
        return result;
      };

      // 清除高亮缓存
      function clearHighlightCache() {
        highlightCache = {};
      }

      // 搜索防抖
      var searchTimeout;

      // 处理搜索
      scope.handleSearch = function() {
        // 清除之前的延时
        if (searchTimeout) {
          clearTimeout(searchTimeout);
        }

        // 延时执行搜索，避免频繁触发
        searchTimeout = setTimeout(function() {
          scope.$apply(function() {
            executeSearch();
          });
        }, 300);
      };

      // 执行搜索的实际逻辑
      function executeSearch() {
        console.log('executeSearch called, keyword:', scope.searchKeyword);
        clearAllHighlights();
        clearHighlightCache();
        scope.searchResults = [];

        var keyword = scope.searchKeyword ? scope.searchKeyword.trim() : '';

        if (!keyword) {
          console.log('No keyword, returning');
          return;
        }

        // 确保 nodeMap 已经构建
        if (!nodeMap || Object.keys(nodeMap).length === 0) {
          console.warn('nodeMap not initialized, rebuilding...');
          buildNodeMap(scope.treeData);
        }

        // 搜索匹配的节点
        scope.searchResults = searchNodes(scope.treeData, keyword);
        console.log('Search keyword:', keyword, 'Results:', scope.searchResults.length);

        if (scope.searchResults.length > 0) {
          // 高亮所有匹配的节点
          scope.searchResults.forEach(function(node) {
            node.highlighted = true;
            // 展开父节点
            expandParents(node);
          });

          // 滚动到第一个匹配的节点
          $timeout(function() {
            var firstNode = scope.searchResults[0];
            var nodeId = firstNode[scope.idField];
            var element = document.getElementById('tree-node-' + nodeId);
            if (element) {
              element.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
          }, 100);
        }
      };

      // 清空搜索
      scope.clearSearch = function() {
        scope.searchKeyword = '';
        clearAllHighlights();
        clearHighlightCache();
        scope.searchResults = [];
      };

      // 初始化
      scope.$watch('treeData', function(newVal, oldVal) {
        if (newVal) {
          // 只在引用变化或首次初始化时重建
          if (newVal !== oldVal || !nodeMap || Object.keys(nodeMap).length === 0) {
            nodeMap = {};
            parentChildMap = {};
            buildNodeMap(newVal);

            // 在 nodeMap 构建完成后，处理初始的 ngModel 值
            if (scope.ngModel && angular.isArray(scope.ngModel) && scope.ngModel.length > 0) {
              var expandedIds = expandSelectedIds(scope.ngModel);
              scope.selectedIds = angular.copy(expandedIds);
            }
          }
          updateTreeCheckState();
        }
      });
    }
  };
}

export default multiLevelTreeDirective;
